/**
 * Carousel widget creator.
 * 
 * Implements a carousel by using CSS classes: carousel, carousel-table, 
 * use-transition, carousel-view and carousel-view*
 */

function CarouselWidget(options) {
	if(!options) options = {};
	if(!options.id) options.id = Widget.uid();
	if(!options.width) options.width = util.width();

	var clazz = options.width >= 320 ? "carousel-320" : "carousel";
	var viewClazz = clazz + "-view";

	var that = Widget(options);

	function tableId() {
		return options.id + "-table";
	}

	function getTable() {
		return $("#"+tableId());
	}
	
	function getViews() {
		return getTable().find("tr:first > td > ." + viewClazz);
	}
	
	function setTableWidth() {
		var width = getViews().size()*options.width;
		getTable().css("width", width + "px");
	}

	that.getHtml = function() {
		return sprintf('<div class="%s" id="%s">\
        	<table summary="Carousel" id="%s" class="use-transition %s0" cellspacing="0" cellpadding="0" border="0">\
			<tbody>\
            <tr></tr>\
			</tbody>\
        	</table>\
    		</div>', clazz, options.id, tableId(), viewClazz);
	};

	function viewId(index) {
		return options.id + "-view-" + index;
	}
	
	function nextViewId() {
		return viewId(getViews().size());
	}

	that.size = function() {
		return getViews().size();
	};

	that.addView = function(content) {
		getTable().find("tr:first").append(sprintf('<td><div class="%s"><div id="%s">%s</div></div></td>', viewClazz, nextViewId(), content));
		setTableWidth();
	};
	
	that.removeViews = function(index) {
		getTable().find("tr:first > td").slice(index).remove();
	};
	
	that.showView = function(index) {
		mwl.show("#" + viewId(index));
		mwl.switchClass('#' + tableId(), viewClazz + '*',viewClazz + index);
	};
	
	that.showOnly = function(index) {
		for(var i = 0; i < getViews().size(); i++) {
			$("#" + viewId(i)).toggle(i == index);
		}
		mwl.switchClass('#' + tableId(), viewClazz + '*',viewClazz + index);
	};

	that.hideViewMwl = function(index) {
		return sprintf("mwl.hide('#%s');", viewId(index));
	};
	
	function wrapTransition(script, noTransition) {
		if(noTransition) return sprintf("mwl.removeClass('#%s','use-transition');%smwl.addClass('#%s','use-transition');", tableId(), script, tableId());
		return script;
	};

	that.linkMwl = function(index, noTransition) {
		//return wrapTransition(sprintf("mwl.show('#%s');mwl.scrollTo('#top');mwl.switchClass('#%s','%s*','%s%s');", viewId(index), tableId(), viewClazz, viewClazz, index), noTransition);
		return wrapTransition(sprintf("mwl.show('#%s');mwl.toggleClass('#top', 'topblock');mwl.scrollTo('#top');mwl.toggleClass('#top', 'topblock');mwl.switchClass('#%s','%s*','%s%s');", viewId(index), tableId(), viewClazz, viewClazz, index), noTransition);
	};
	
	return that;
}
